#-*- coding: utf-8 -*-

import requests
import json
import pandas as pd
import numpy as np
import warnings
import os


df_id = pd.read_excel('test_3000_postman.xlsx', dtype='str') # 读取3000条原始三要素
df_id = df_id.fillna('')
#df_id = df_id.sort_values(by='客户数据编号', ascending=True)
#del df_id['y变量']

df_id.head(5)

body_model = {
    "brData": {
            'flag_populationderivation':'',
            'flag_multiplemodela':'',
            'flag_applyloanstr':'',
            'flag_totalloan':'',
            'flag_quantilelevel':'',
            'flag_ApplyFeature':'',
            'als_d15_id_nbank_oth_orgnum':'',
            'ql_d15_id_nbank_top_orgnum':'',
            'mma_var236':'',
            'alf_time_intedays_d30_mean':'',
            'als_m6_id_nbank_cf_orgnum':'',
            'alf_apirisk_time_lenth_d90_sum':'',
            'tl_cell_t10_nbank_reamt':'',
            'pd_cell_city_rent_sort':'',
        
    },
    "extraData": {"id":"522631199103218515","cell":"18285598258","user_date":"2021-07-14","name":"吴荣远"},
    "outLevel":"1",
    "strategyType": None,
    "pointType": "scoreconsonxmlr",
    "scoreData": "",
    "scoreBaseMealId": None,
    "swiftNumber": "",
    "scoreType": '[{"score":"scoreconsonxmlr","api":"S2_0"}]',
    "apiCode": "4002474"
}


body = body_model.copy()
body_list = []
#读取3000条数据
df = pd.read_csv('test_3000_dts_final.csv',encoding='utf-8', dtype='str', sep=',')
df = df.fillna('')
df['cus_num'] = df['cus_num'].astype(int)
df.sort_values(by='cus_num', inplace=True)
df = df.reset_index(drop = True)

list_vars = list(body['brData'].keys())
list_extra = list(body['extraData'].keys())
list_vars.extend(list_extra)
list_vars.append('cus_num')
df = df[list_vars]
score = []
df_id = df_id.copy()
df_id['score'] = ''


for i in range(0, 3000):
    id_cell = df_id[df_id['客户数据编号'] == str(df.iloc[i]['cus_num'])]
    body = body_model.copy()
    for key1 in body_model['brData']:
        body['brData'][key1] = df.iloc[i][key1]
    for key2 in body_model['extraData']:
        if key2 == 'id':
            body['extraData'][key2] = id_cell.iloc[0]['身份证号']
        elif key2 == 'cell':
            body['extraData'][key2] = id_cell.iloc[0]['手机号']
        elif key2 == 'name':
            body['extraData'][key2] = id_cell.iloc[0]['姓名']
        else:
            body['extraData'][key2] = df.iloc[i][key2]

    body['inparam'] = body['extraData']
    body['brData'] = json.dumps(body['brData'])
    body['inparam'] = json.dumps(body['inparam'])
    body['extraData'] = json.dumps(body['extraData'])
    #print(i,body)
    re_ = requests.post('http://feature-k8s.100credit.cn/v1/get_model_result', json=body)
    re_ = re_.json()
    try:
        df_id.loc[df_id['客户数据编号']== str(df.iloc[i]['cus_num']), 'score'] = re_['resultData']['pointResult']['scoreconsonxmlr']
        # df_id.loc[df_id['客户数据编号']== str(df.iloc[i]['cus_num']), 'var'] = re_['resultData']['scoreData']['scoreconsonxmlr']['derive']
    except:
        df_id.loc[df_id['客户数据编号'] == str(df.iloc[i]['cus_num']), 'score'] = ''
        # df_id.loc[df_id['客户数据编号'] == str(df.iloc[i]['cus_num']), 'var'] = ''

    # 衍生变量输出    
    # ft_data = json.loads(re_['resultData']['scoreData']['scoreconsonxmlr']['derive'])
    # for key,value in ft_data.items():
    #     df_id.loc[df_id['客户数据编号']== str(df.iloc[i]['cus_num']), key] = value
df_id.head(10)

df_id['客户数据编号'] = df_id['客户数据编号'].astype('int')

df = df.drop(columns=[ 'id', 'cell', 'user_date', 'name'])
df.rename(columns = {'cus_num':'客户数据编号'},inplace=True)
df

result = pd.merge(df_id,df,how='left',on='客户数据编号')
result

result.to_excel('3000条线上提测结果.xlsx', index=False, encoding='utf_8_sig')
 
    
    